define(function(require, exports, module){

	var $ = require('jquery');
	require('jbox');
	require('../util/getURL.js');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('jquery/jquery-validation/1.11.0/messages_zh');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('jbox');
	
	$("#regist-form").validate({
		rules : {
			name :{
				required:true,
				remote:$CONFIG.base_url+"/regist/check_name"
			},
			loginName : {
				required : true,
				remote : $CONFIG.base_url+"/regist/check_login_name"
			},
			plainPassword : {
				required : true
			},
			rePassword:{
				required : true,
				equalTo:"#plainPassword"
			}
		},
		messages : {
			name : {
				required:'请输入昵称',
				remote:'昵称已存在'
			},
			loginName : {
				required : '请输入用户名',
				remote : '手机号已经存在'
			},
			plainPassword : {
				required : '请输入密码'
			},
			rePassword:{
				required : '请输入确认密码!',
				equalTo:"请确认两次密码输入一致!"
			}
		},
		errorLabelContainer : "#error"
	});
	$('.img_captcha_login').on('click', function(){$("#img_captcha_login").attr("src",$CONFIG.base_url+"/servlet/captchaCode?t=" + Math.random());});
	$('.img_captcha_forget').on('click', function(){$("#img_captcha_forget").attr("src",$CONFIG.base_url+"/servlet/captchaCode?t=" + Math.random());});
	var href = window.location.href;
	var flag = href.substr(href.indexOf("?")+1,4);
	if(flag == 'code'){
		var CODE = href.substring(href.indexOf('=')+1);
	}else{
		var accessToken = window.location.hash.substring(1);
		var access_token = accessToken.substring(accessToken.indexOf("=")+1,accessToken.indexOf("&"));
	}

	$.ajax({
		  type: 'POST',
		  url:$CONFIG.base_url+"/login/bind",
		  data:{token: access_token},
		  async: false,
		  dataType: "json",
		  success: function(e){
			  if(e.token != null){
				  $.ajax({
					  type: 'POST',
					  url:$CONFIG.base_url+"/login",
					  data:{username:e.user.loginName,authcType:'SOCIAL_AUTHC'},
					  async: false,
					  success: function(e){
						  window.location = $CONFIG.base_url+"/home";
					  }
				});
			  }else if(flag != 'code'){
				  $('#bind-page').show();
				  //获取用户信息
				  $.ajax({
					  type: 'GET',
					  url: 'https://graph.qq.com/oauth2.0/me?'+accessToken,
					  async: false,
					  dataType: "jsonp",
					  jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
					  jsonpCallback:"callback",
					  success: function(o){
						  $.ajax({
							  type: 'POST',
							  url:$CONFIG.base_url+"/third/get_user_info",
							  data:{url: 'https://graph.qq.com/user/get_user_info?'+accessToken+'&oauth_consumer_key=101152891&openid='+o.openid},
							  async: false,
							  dataType: "json",
							  success: function(e){
								  $('#type').text("腾讯QQ帐号");
								  $('#bindType').val(1);
								  var $info = $.parseJSON(e.msg);
								  $("#userImg").attr("src",$info.figureurl_qq_2);
								  $('#userNickName').text($info.nickname);
								  
								  $('#url').val($info.figureurl_qq_2);
								  $('.username').val($info.nickname);
							  }
						});
					 }
				  });
			  }else if(flag == 'code'){
				  $(".loginpage").attr({style:"display:block;"});
				  $.ajax({
					  type: 'POST',
					  url:$CONFIG.base_url+"/third/get_access_token",
					  data:{url: 'https://api.weibo.com/oauth2/access_token?client_id=2793479754&client_secret=caec1a383396e5605f59ce48f234ae80&grant_type=authorization_code&redirect_uri=http://yami.lanbaoo.com/login/bind&code='+CODE,},
					  async: false,
					  dataType: "json",
					  success: function(e){
					  	var info = $.parseJSON(e.msg);
					  	access_token = info.access_token;	
						  	$.ajax({
							  type: 'GET',
							  url: 'https://api.weibo.com/2/users/show.json',
							  data:{'access_token':info.access_token,
									'uid':info.uid
								},
							  async: false,
							  dataType: "jsonp",
					  		  jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
					  		  jsonpCallback:"callback",
							  success: function(o){
							  	  var $info = o.data;
								  $("#userImg").attr("src",$info.avatar_hd);
								  $('#userNickName').text($info.screen_name);
								  $('#type').text("新浪微薄帐号");
								  $('#bindType').val(2);
								  $('#url').val($info.avatar_hd);
								  $('.username').val($info.screen_name);								   
							 }
						  });
						  
					  }
				  });
			  }
		  }
	});
	//绑定新帐号
	  $('#registUser').click(function(e){
		  if(!$(".checkbox-login").prop("checked")){
			  $.jBox.tip("您还没有同意我们的服务条款！");
			  return;
		  }
		  if(!$("#regist-form").valid()){
				return;
		  }
			var postData = $.toJSON(form2js('regist-form', '.', true));
			$.ajax({
              type: "POST",
              dataType : 'json',
              url:$CONFIG.base_url+"/api/user/bind/add_user",
              data:postData,
              contentType : "application/json",
              async: false,
	            error: function(data) {
	            	$.jBox.tip("创建新帐号异常！");
	            },
	            success: function(data) {
	            	$.ajax({
	            		cache: true,
			            type: "POST",
			            url:$CONFIG.base_url+"/login",
			            data:{username:data.user.loginName,authcType:'SOCIAL_AUTHC'},
			            async: false,
	                    error: function(request) {
	                        $.jBox.tip("Connection error");
	                    },
	                    success: function(e) {
	                        //var user = new Object();
	                        var t = new Object();
	                        //user["id"] = e.user.id;
	                        t["user"]=data.user;
	                        t["token"]=access_token;
	                        t["platform"]="3";
	                        t["bindType"]="1";
	                        t = $.toJSON(t);
	                        $.ajax({
	                            cache: true,
	                            type: "POST",
	                            dataType : 'json',
	                            url:$CONFIG.base_url+"/api/user/bind",
	                            data:t,
	                            contentType : "application/json",
	                            async: false,
	                            error: function(request) {
	                                $.jBox.tip("绑定失败！");
	                            },
	                            success: function(e) {
	                            	$.jBox.tip("创建新用户成功！");
	                            	window.location = $CONFIG.base_url+"/home";
	                            }
	                        });
	                    }
	                });
	            }
	        });
			
		});
	  //绑定已有帐号
	  $('#bindOld').click(function(e){
			$.ajax({
	            cache: true,
              type: "POST",
              url:$CONFIG.base_url+"/login/rest",
              data:$('#login-form').serialize(),
              async: false,
	            error: function(request) {
	            	$.jBox.tip("登陆失败！");
	            },
	            success: function(data) {
	            	$.ajax({
	            		cache: true,
			            type: "POST",
			            url:$CONFIG.base_url+"/login",
			            data:{username:data.user.loginName,authcType:'SOCIAL_AUTHC'},
			            async: false,
	                    error: function(request) {
	                        $.jBox.tip("Connection error");
	                    },
	                    success: function(e) {
	                        //var user = new Object();
	                        var t = new Object();
	                        //user["id"] = e.user.id;
	                        t["user"]=data.user;
	                        t["token"]=access_token;
	                        t["platform"]="3";
	                        t["bindType"]=$('#bindType').val();
	                        t = $.toJSON(t);
	                        $.ajax({
	                            cache: true,
	                            type: "POST",
	                            dataType : 'json',
	                            url:$CONFIG.base_url+"/api/user/bind",
	                            data:t,
	                            contentType : "application/json",
	                            async: false,
	                            error: function(request) {
	                                $.jBox.tip("绑定失败！");
	                            },
	                            success: function(e) {
	                            	$.jBox.tip("绑定成功");
	                            	window.location = $CONFIG.base_url+"/home";
	                            }
	                        });
	                    }
	                });
	            }
	        });
		});
});
